<?php
/**
 * 上传文件接口
 */
namespace app\admin\model;

use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use think\Db;
require_once env('ROOT_PATH').'/vendor/teg1c/thinkphp-qiniu-sdk/qiniu_php_driver/autoload.php';
class UpFile{
    protected $file = [];
    protected $loc = './uploads/';
    protected $name = [];

    /**设置文件
     * @return $this
     */
    public function setFile(){
        $this->file = request()->file();
        return $this;
    }

    /**设置本地存储
     * @param null $path
     * @return $this
     */
    public function setLoc($path=null){
        if($path){
            $this->loc = $path;
        }
        return $this;
    }

    /**获取本地存储
     * @param null $path
     * @return string|null
     */
    public function getLoc($path=null){
        if(!$path){
            $path = rtrim('.'.trim($this->loc,'.'),'/').'/';
            if($modular = session('modular')){
                $path = $path.$modular;
            }elseif ($mod = request()->module()){
                $path = $path.$mod;
            }
        }
        return $path;
    }

    /**七牛存储
     * @param $file
     */
    public function qiniu($index,$file){
        $qiniu = $this->isQiNiu();
        $fileinfo = $file->getInfo();
        $data['yuan_name'] = $fileinfo['name'];
        $ak = $qiniu['ak'];
        $sk = $qiniu['sk'];
        $bucket = $qiniu['bucket'];
        $auth = new Auth($ak,$sk);
        $uploadMgr = new UploadManager();
        $filePath = $fileinfo['tmp_name'];
        if(!$name = $this->name[$index]??null){
            $types = explode('.',$fileinfo['name']);
            $type = end($types);
            $name =uniqid().'.'.$type;
        }else{
            $name = uniqid().$name;
        }
        $token = $auth->uploadToken($bucket,$name);
        list($ret,$err) = $uploadMgr->putFile($token,$name,$filePath);
        if($err!==null){
            return false;
        }else{
            $data['new_name'] = $name;
        }
        $data['path'] = str_replace("\\","/",$qiniu['url'].'/'.$name);
        $data['quan_path'] = $data['path'];
        return $data;
    }

    /**本地存储
     * @param $file
     */
    public function local($index,$file,$quanpath){
        $newinfo = $file->getInfo();
        $data['yuan_name'] = $newinfo['name'];
        if(!$quanpath){
            $info = $file->move( $this->getLoc());
        }else{
            $info = $file->move($this->getLoc());
        }
        $data['path'] = str_replace('\\','/',rtrim(trim($this->getLoc(),'.'),'/').'/'.$info->getSaveName());
        $data['new_name'] = $info->getFilename();
        $data['quan_path'] = request()->domain().$data['path'];
        return $data;
    }

    /**上传文件
     * @param bool是否获取key $iskey
     * @param null 相对路径 $path
     * @param null 自定义路径 $quanpath
     * @return array
     */
    public static function upfiles($name=[],$iskey=false,$path=null,$quanpath=null){
        $obj = new UpFile();
        if($name){
            $obj->name = $name;
        }
        $obj->setLoc($path);
        $obj->setFile();
        $newdata = [];
        $index = 0;
        foreach ($obj->file as $key=>$value){
            if($iskey){
                if($obj->isQiNiu()){
                    $newdata[$key] = $obj->qiniu($index,$value);
                }else{
                    $newdata[$key] = $obj->local($index,$value,$quanpath);
                }
            }else{
                if($obj->isQiNiu()){
//                    return $obj->qiniu($index,$value);
                    $newdata[] = $obj->qiniu($index,$value);
                }else{
                    $newdata[] = $obj->local($index,$value,$quanpath);
                }
            }
            $index++;
        }
        if($newdata){
            return $obj->getEnclosure($newdata);
        }else{
            return [];
        }
    }

    /**判断是否使用七牛云存储
     * @return array|bool|\PDOStatement|string|\think\Model|null
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function isQiNiu(){
        $data = Db::name(getTable('qiniu'))
            ->where('status',1)
            ->find();
        if($data){
            return $data;
        }else{
            return false;
        }
    }

    /**添加到附件表
     * @param array $data
     * @return bool
     * @throws \think\Exception
     */
    public function getEnclosure($data=[]){
        if($data){
            $newdata = [];
            foreach ($data as $key=>$value){
                $value['status'] = 1;
                $value['create_time'] = time();
                $value['id'] = Db::name(getTable('enclosure'))
                    ->insertGetId($value);
                $newdata[$key] = $value;
            }
            return $newdata;
        }else{
            return false;
        }
    }
    public static function delete($id,$tr=false){
        $data = Db::name(getTable('enclosure'))
            ->where('id','in',$id)
            ->select();
        $obj = new UpFile();
        foreach ($data as $value){
            if($tr){
                if(strstr($value['path'],'http')){
//
                    $obj->deleteQiNiu($value['new_name']);
                }else{
//                    return 2;
                    $obj->deleteLoc($value['path']);
                }
                Db::name(getTable('enclosure'))->where('id',$value['id'])->delete();
            }else{
                $value['status'] = 0;
                Db::name(getTable('enclosure'))
                    ->where('id',$value['id'])
                    ->update([
                       'status'=>0
                    ]);
            }
        }
        return true;
    }

    /**本地删除文件
     * @param null $path
     * @return bool
     */
    public function deleteLoc($path=null){
        if(is_file('.'.$path)){
            chmod('.'.$path,0777);
            unlink('.'.$path);
            return true;
        }
        return false;
    }

    /**七牛删除文件
     * @param null $name
     * @return bool
     */
    public function deleteQiNiu($name=null){
        $qiniu = $this->isQiNiu();
//        return 1;
        $key =$name;
        $ak = $qiniu['ak'];
        $sk = $qiniu['sk'];
        $bucket  = $qiniu['bucket'];
        $auth = new Auth($ak,$sk);
        $bucketManager = new \Qiniu\Storage\BucketManager($auth);
        $err = $bucketManager->delete($bucket,$key);
        if($err){
            return false;
        }else{
            return true;
        }
    }
    public static function FenPian(){
        usleep(5000);
        $data = request()->param();
        $name = $data['name'];
        $names = explode('.',$name);
        $names = $names[0];
        if(session('modular')){
            $path = './uploads/'.session('modular').'/temp/'.$names;
            $npath = './uploads/'.session('modular').'/temp/';
        }else{
            $path = './uploads/'.request()->module().'/temp/'.$names;
            $npath = './uploads/'.request()->module().'/temp/';
        }
        if(!is_dir($path)){
            mkdir($path,0777,true);
        }
        $obj = new UpFile();
        $path = $path.'/'.$names.'_'.$data['index'].'.part';
        $file = request()->file('file');
        $fileinfo = $file->getInfo();
        move_uploaded_file($fileinfo['tmp_name'],$path);
        $done = true;
        $names = explode('.',$data['name']);
        $names = $names[0];
        for($a=1;$a<=(int)$data['number'];$a++){
            if(!file_exists($npath.$names.'/'.$names.'_'.$a.'.part')){
                $done = false;
            }
        }
//        return $npath.$names;
        if($done){
            $datas = $obj->hebin($data);
//            return $datas;
            $newdatas = $obj->getEnclosure([$datas]);
            $newdatas[0]['success'] = 1;
            return $newdatas[0];
        }
        $data['success'] = 0;
        return $data;
    }

    /**分片合并
     * @param $data
     * @return mixed
     */
    public function hebin($data){
        sleep(1);
        $newdata['yuan_name'] = $data['name'];
        $names = explode('.',$data['name']);
        $type = end($names);
        $names = $names[0];
        $filepath = '/uploads/';
        if(session('modular')){
            $filepath = $filepath.session('modular');
            $path = './uploads/'.session('modular').'/temp/'.$names;
        }else{
            $path = './uploads/'.request()->module().'/temp/'.$names;
            $filepath = $filepath.request()->module();
        }
        $str = '';
        for ($a=1;$a<=$data['number'];$a++){
            if(is_file($path.'/'.$names.'_'.$a.'.part')){
                $str .= file_get_contents($path.'/'.$names.'_'.$a.'.part');
                unlink($path.'/'.$names.'_'.$a.'.part');
            }
        }
        $newdata['new_name'] = uniqid().'.'.$type;
        $filepath = $filepath.'/'.date('Ymd',time());
        if(!is_dir('.'.$filepath)){
            mkdir('.'.$filepath,0777,true);
        }
        if(file_put_contents('.'.$filepath.'/'.$newdata['new_name'],$str)){
            $newdata['path'] = $filepath.'/'.$newdata['new_name'];
            $newdata['quan_path'] = request()->domain().$filepath.'/'.$newdata['new_name'];
            rmdir($path);
        }
        if($this->isQiNiu()){
            if(is_file('.'.$newdata['path'])){
                $newdata['path'] = $this->saveToQiNiu('.'.$newdata['path'],$newdata['new_name']);
            }
        }
        return $newdata;
    }

    /**将图片上传到七牛云
     * @param $path
     * @param $key
     * @return bool|string
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function saveToQiNiu($path,$key){
        $qiniu = $this->isQiNiu();
        $ak = $qiniu['ak'];
        $sk = $qiniu['sk'];
        $bucket = $qiniu['bucket'];
        $auth = new Auth($ak,$sk);
        $uploadMgr = new UploadManager();
        $filePath = $path;
        $name = $key;
        $token = $auth->uploadToken($bucket,$name);
        list($ret,$err) = $uploadMgr->putFile($token,$name,$filePath);
        if($err!==null){
            return false;
        }else{
            chmod($path,0777);
            if(is_file($path)){
                unlink($path);
            }
            return $qiniu['url'].'/'.$name;
        }
    }
    public static function base64UpFile($path='/uploads/juyou/',$file_key='file'){
        $file = request()->param($file_key);
        $file = str_replace(' ','+',$file);
        if(preg_match('/^(data:\s*image\/(\w+);base64,)/',$file,$result)){
            $type = $result[2];
            $file_name = uniqid().'.'.$type;
            if(!is_dir('.'.$path.date('Ymd',time()))){
                chmod('.'.$path,0777);
                mkdir('.'.$path.date('Ymd',time()));
            }
            $path =$path.date('Ymd',time()).'/'.$file_name;
            $str =explode(',',$file);
            if(file_put_contents('.'.$path,base64_decode($str[1]))){
                $data['path'] = $path;
                $data['yuan_name'] = $file_name;
                $data['new_name'] = $file_name;
                $obj = new UpFile();
                $data = $obj->getEnclosure([$data]);
                return $data[0];
            }else{
                return false;
            }
        }else{
            return false;
        }
    }
}